package com.zp.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.core.utils.TreeBuildUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.satoken.utils.LoginHelper;
import com.zp.system.api.entity.LoginUser;
import com.zp.system.api.entity.SysOrg;
import com.zp.system.entity.bo.SysOrgBo;
import com.zp.system.entity.vo.SysOrgVo;
import com.zp.system.mapper.SysOrgMapper;
import com.zp.system.service.ISysOrgService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 机构Service业务层处理
 *
 * @author zhang peng
 * @date 2022-12-16
 */
@RequiredArgsConstructor
@Service
public class SysOrgServiceImpl implements ISysOrgService {

    private final SysOrgMapper baseMapper;

    /**
     * 查询机构
     */
    @Override
    public SysOrgVo queryById (String orgId) {
        return baseMapper.selectVoById(orgId);
    }

    /**
     * 查询机构列表(分页)
     */
    @Override
    public TableDataInfo<SysOrgVo> queryPageList (SysOrgBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOrg> lqw = buildQueryWrapper(bo);
        Page<SysOrgVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询机构列表(不分页)
     */
    @Override
    public List<SysOrg> queryList (SysOrg sysOrg) {
        SysOrgBo bo = new SysOrgBo();
        BeanUtil.copyProperties(sysOrg, bo);
        LambdaQueryWrapper<SysOrg> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<SysOrg> buildQueryWrapper (SysOrgBo bo) {
        LambdaQueryWrapper<SysOrg> lqw = Wrappers.lambdaQuery();
        LoginUser loginUser = LoginHelper.getLoginUser();
        lqw.like(StringUtils.isNotBlank(bo.getOrgName()), SysOrg::getOrgName, bo.getOrgName());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgCode()), SysOrg::getOrgCode, bo.getOrgCode());
        lqw.eq(StringUtils.isNotBlank(loginUser.getOrgId()), SysOrg::getOrgId, loginUser.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), SysOrg::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), SysOrg::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SysOrg::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getLinkMan()), SysOrg::getLinkMan, bo.getLinkMan());
        lqw.eq(StringUtils.isNotBlank(bo.getApplyStatus()), SysOrg::getApplyStatus, bo.getApplyStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getParentId()), SysOrg::getParentId, bo.getParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getParentIds()), SysOrg::getParentIds, bo.getParentIds());
        lqw.eq(StringUtils.isNotBlank(bo.getRegion()), SysOrg::getRegion, bo.getRegion());
        lqw.eq(StringUtils.isNotBlank(bo.getRegionCode()), SysOrg::getRegionCode, bo.getRegionCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgImg()), SysOrg::getOrgImg, bo.getOrgImg());
        lqw.eq(StringUtils.isNotBlank(bo.getSocialCode()), SysOrg::getSocialCode, bo.getSocialCode());
        lqw.eq(StringUtils.isNotBlank(bo.getProvince()), SysOrg::getProvince, bo.getProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), SysOrg::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getCounty()), SysOrg::getCounty, bo.getCounty());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliverMark()), SysOrg::getDeliverMark, bo.getDeliverMark());
        lqw.eq(StringUtils.isNotBlank(bo.getSuperviseMark()), SysOrg::getSuperviseMark, bo.getSuperviseMark());
        lqw.eq(StringUtils.isNotBlank(bo.getCureMark()), SysOrg::getCureMark, bo.getCureMark());
        lqw.eq(StringUtils.isNotBlank(bo.getArchivesMark()), SysOrg::getArchivesMark, bo.getArchivesMark());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgClass()), SysOrg::getOrgClass, bo.getOrgClass());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgLevel()), SysOrg::getOrgLevel, bo.getOrgLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysOrg::getStatus, bo.getStatus());
        lqw.eq(bo.getOrderNum() != null, SysOrg::getOrderNum, bo.getOrderNum());
        return lqw;
    }

    /**
     * 新增机构
     */
    @Override
    public Boolean insertByBo (SysOrgBo bo) {
        SysOrg add = BeanUtil.toBean(bo, SysOrg.class);
        validEntityBeforeSave(add);
        add.setOrgId(bo.getOrgCode());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setOrgId(add.getOrgCode());
        }
        return flag;
    }

    /**
     * 修改机构
     */
    @Override
    public Boolean updateByBo (SysOrgBo bo) {
        SysOrg update = BeanUtil.toBean(bo, SysOrg.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (SysOrg entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除机构
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param sysOrgList 机构列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<String>> buildOrgTreeSelect (List<SysOrg> sysOrgList) {
        if (CollUtil.isEmpty(sysOrgList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(sysOrgList, (org, tree) ->
                tree.setId(org.getOrgId())
                        .setParentId(org.getParentId())
                        .setName(org.getOrgName())
                        .setWeight(org.getOrderNum()));
    }

    ;

    /**
     * 修改机构状态
     *
     * @param sysOrg 机构信息
     * @return 结果
     */
    @Override
    public int updateOrgStatus (SysOrg sysOrg) {
        return baseMapper.updateById(sysOrg);
    }


    /**
     * 校验机构名称是否唯一
     *
     * @param bo 机构信息
     * @return 结果
     */
    @Override
    public String checkOrgNameUnique (SysOrgBo bo) {
        SysOrg org = BeanUtil.toBean(bo, SysOrg.class);
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysOrg>()
                .eq(SysOrg::getOrgName, org.getOrgName())
                .ne(ObjectUtil.isNotNull(org.getOrgId()), SysOrg::getOrgId, org.getOrgId()));
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验机构代码是否唯一
     *
     * @param bo 机构信息
     * @return 结果
     */
    @Override
    public String checkOrgCodeUnique (SysOrgBo bo) {
        SysOrg org = BeanUtil.toBean(bo, SysOrg.class);
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysOrg>()
                .eq(SysOrg::getOrgCode, org.getOrgCode())
                .ne(ObjectUtil.isNotNull(org.getOrgId()), SysOrg::getOrgId, org.getOrgId()));
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    ;
}
